<!--
 * @Author: weikang
 * @Description:
 * @Date: 2023-12-22 23:13:35
 * @LastEditTime: 2024-04-07 22:54:04
 * @FilePath: \env-manager-pc\src\views\document\manager\create\access\index.vue
-->
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import Edit from './edit.vue'
import type { AccountForm } from './page'
import type { doLoading } from '@/types/page'
import { QueryObj } from '@/utils/dataHook/data'
import { usePage } from '@/utils/commonHook'
import userApi from '@/api/modules/user'
import { ModelType } from '@/types/common'

import useEntStore from '@/store/modules/ent'

const currentEntInfo: any = computed(() => {
  return useEntStore().currentEntData.baseInfo
})

const editRef = ref()

const searchData = reactive(new QueryObj({
  objType: 'DIM.FilterCollection',
  Filters: [
    'DIM.Authorizations.Filters.CodeFilter',
    'DIM.Authorizations.Filters.NameFilter', 'DIM.Authorizations.Filters.ContactTelFilter', 'DIM.Authorizations.Filters.MsgTelFilter'],
}))
const loading = ref(false)

const tableData = ref([])
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)

function search() {
  page.PageNum = 1
  getTableData()
}

async function getTableData() {
  loading.value = true
  const params = searchData.getQuery()
  const res = await userApi.GetAccountList({
    objFilter: {
      Type: 'DIM.FilterCollection',
      LogicOperator: 0,
      Filters: [...params.Filters, {
        Type: 'DIM.Authorizations.Filters.AffiliatedObjIDFilter',
        ObjType: 'Enterprise',
        Value: [currentEntInfo.value.ObjID],
      },
      ],
    },
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  // console.log('%c [ res ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  const { Rows, RecordsetCount } = res as any
  tableData.value = Rows || []
  page.RecordsetCount = RecordsetCount
}

getTableData()

function toEdit(row: any) {
  editRef.value.open({
    data: row,
    type: ModelType.edit,
  })
}

function toCreate() {
  editRef.value.open({
    type: ModelType.add,
  })
}
async function submitEdit(formData: AccountForm, doLoading: doLoading) {
  try {
    doLoading(true)
    const isCreate = !formData.AccountObjID
    isCreate
      ? await userApi.AddAccount({
        accountInfo: formData,
      })
      : await userApi.UpdateAccount({
        accountInfo: formData,
      })
    getTableData()
    editRef.value.close()
    ElMessage.success({
      message: isCreate ? '新增成功' : '编辑成功',
      type: 'success',
    })
  }
  catch (e) {
    doLoading(false)
  }
}

async function toDel(row: AccountForm) {
  await ElMessageBox.confirm(`确定删除账户 ${row.Name} 吗？`, '提示', {
    type: 'warning',
  })
  await userApi.DeleteAccount({ accountObjID: row.AccountObjID })
  ElMessage.success({
    message: '删除成功',
    type: 'success',
  })
  getTableData()
}
</script>

<template>
  <div>
    <ElForm label-width="100" class="mb-[20px]">
      <ElRow>
        <ElCol :span="6">
          <ElFormItem label="账号">
            <ElInput v-model="searchData['DIM.Authorizations.Filters.CodeFilter']" clearable />
          </ElFormItem>
        </ElCol>
        <ElCol :span="6">
          <ElFormItem label="姓名">
            <ElInput v-model="searchData['DIM.Authorizations.Filters.NameFilter']" clearable />
          </ElFormItem>
        </ElCol>
        <ElCol :span="6">
          <ElFormItem label="联系电话">
            <ElInput v-model="searchData['DIM.Authorizations.Filters.ContactTelFilter']" clearable />
          </ElFormItem>
        </ElCol>
        <ElCol :span="6">
          <ElFormItem label="消息推送电话">
            <ElInput v-model="searchData['DIM.Authorizations.Filters.MsgTelFilter']" clearable />
          </ElFormItem>
        </ElCol>
        <ElCol :span="6" :push="18" class="flex flex-justify-end">
          <ElButton type="primary" @click="search">
            查询
          </ElButton>
          <ElButton type="success" @click="toCreate">
            新增
          </ElButton>
        </ElCol>
      </ElRow>
    </ElForm>

    <div v-auto-height="85">
      <vxe-table
        auto-resize border height="100%" :data="tableData" :loading="loading"
        :row-config="{ isCurrent: true }"
      >
        <VxeColumn type="seq" title="序号" width="80" />
        <VxeColumn field="AccountCode" title="账号" min-width="140" show-overflow />
        <VxeColumn field="Name" title="姓名" min-width="200" />
        <VxeColumn field="AffiliatedObjName" title="隶属单位" min-width="220" />
        <VxeColumn field="Roles" title="角色" min-width="150">
          <template #default="{ row }">
            <el-tag v-for="(item, index) in Object.keys(row.Roles).map((key) => row.Roles[key])" :key="index" class="mb-[5px] mr-[10px]">
              {{ item }}
            </el-tag>
          </template>
        </VxeColumn>
        <VxeColumn field="StateDescription" title="账号状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.StateID === 1" type="success">
              正常
            </el-tag>
            <el-tag v-else type="danger">
              禁用
            </el-tag>
          </template>
        </VxeColumn>
        <VxeColumn field="ExpirTime" title="有效期" width="140">
          <template #default="{ row }">
            {{ row.ExpirTime || '无期限' }}
          </template>
        </VxeColumn>
        <VxeColumn field="ContactTel" title="联系电话" width="180" />
        <VxeColumn field="MsgTel" title="消息推送电话" width="180" />
        <VxeColumn field="WxOpenID" title="绑定微信号" width="140" />
        <VxeColumn field="LogonTime" title="最后登录时间" width="140" />
        <VxeColumn field="operate" title="操作" width="160" fixed="right">
          <template #default="{ row }">
            <ElButton type="success" link @click="toEdit(row)">
              编辑
            </ElButton>
            <ElButton type="danger" link @click="toDel(row)">
              删除
            </ElButton>
          </template>
        </VxeColumn>
      </vxe-table>
    </div>
    <ElPagination
      class="mt-4" :page-size="page.PageSize" :total="page.RecordsetCount" :current-page="page.PageNum"
      layout="total, sizes, prev, pager, next, jumper" :page-sizes="[20, 50, 100]" @current-change="pageNumChange"
      @size-change="pageSizeChange"
    />
    <Edit ref="editRef" :current-ent-info="currentEntInfo" @submit="submitEdit" />
  </div>
</template>
